package com.wenc.psi.fgmt.homefgmt;

import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.wenc.psi.R;
import com.wenc.psi.dao.CustomerDao;
import com.wenc.psi.databinding.FragmentChoiceCustomerBinding;
import com.wenc.psi.pojo.Customer;
import com.wenc.psi.rvAdapter.CustomerAdapter;
import com.wenc.psi.vmd.SaleViewModel;

import java.util.List;

public class ChoiceCustomerFragment extends Fragment {
    private FragmentChoiceCustomerBinding binding;
    private CustomerAdapter customerAdapter;
    private SaleViewModel saleViewModel;
    private List<Customer> customerList;
    private CustomerDao customerDao;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        customerDao = new CustomerDao();
        new Thread(()->{
            customerList = customerDao.getAllData();
            System.out.println(customerList.size());
        }).start();
        while (true) {
            if (customerList != null) break;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_choice_customer, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        saleViewModel = new ViewModelProvider(getActivity()).get(SaleViewModel.class);

        customerAdapter = new CustomerAdapter();
        customerAdapter.setCustomerList(customerList);
        binding.rvCustomer.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.rvCustomer.setAdapter(customerAdapter);


        // 点击取消处理
        binding.choiceCustomerCancel.setOnClickListener(v -> {
            getActivity().getSupportFragmentManager().beginTransaction().hide(this).commit();
        });
        // 点击完成处理
        binding.choiceCustomeFinish.setOnClickListener(v -> {
            getActivity().getSupportFragmentManager().beginTransaction().hide(this).commit();
        });
        // 点击选择客户
        customerAdapter.setOnItemClickListener(new CustomerAdapter.OnItemClickListener() {
            @Override
            public void onItemChoiceClick(Customer customer) {
                saleViewModel.setCustomer(customer.getName(), customer.getId());
            }
        });
    }
}